package com.example.demo.service.impl;

import com.example.demo.commen.ResultCode;
import com.example.demo.dao.ArticleReplyMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.Article;
import com.example.demo.model.ArticleReply;
import com.example.demo.service.IArticleReplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Autowired
    ArticleServiceImpl articleService;
    @Autowired
    ArticleReplyMapper articleReplyMapper;
    @Override
    public void createArticleReply(ArticleReply articleReply) {
        System.out.println(articleReply);
        if(articleReply==null||articleReply.getArticleId()==null||
           articleReply.getPostUserId()==null||!StringUtils.hasLength(articleReply.getContent())){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        articleReply.setReplyId(null);   //这个没有，给一个初始值
        articleReply.setReplyUserId(null);  //这个没用，给一个初始值
        articleReply.setLikeCount(0);  //这个没用，给一个初始值
        articleReply.setState((byte)0);
        articleReply.setDeleteState((byte) 0);
        articleReply.setUpdateTime(new Date());
        articleReply.setCreateTime(new Date());
      int flag =  articleReplyMapper.insertSelective(articleReply);        //新增回复
        if(flag!=1){
            throw  new ApplicationException(ResultCode.FAILED.toString());
        }

        articleService.addOneReplyCountById(articleReply.getArticleId());    //更新帖子表的回复数
        log.info("帖子回复成功");
    }

    @Override
    public List<ArticleReply> getListArticleReplyByArticleId(Long articleId) {
        if(articleId==null||articleId<=0){
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }

        Article article = articleService.selectArticleById(articleId);
        if(article==null||article.getId()<=0||article.getState()==1||article.getDeleteState()==1){
            throw  new ApplicationException("帖子出现异常");
        }

        List<ArticleReply> lists = articleReplyMapper.selectArticleReplyByArticleId(articleId);
        if(lists==null){
            throw new ApplicationException("此帖子无回复内容");
        }
        return lists;
    }
}
